<template>
  <div class="app-container">
    <!-- 调度日志 -->
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="执行器" prop="jobGroup">
        <dict-selector :dictData="jobGroupList" :value="queryParams.jobGroup" @change="onJobGroupSelectChanger" style="width:240px" />
      </el-form-item>
      <el-form-item label="任务" prop="jobId">
        <dict-selector :dictData="jobInfoList" :value="queryParams.jobId" @change="(val) => queryParams.jobId=val" style="width:240px" />
      </el-form-item>
      <el-form-item label="任务Handler" prop="executorHandlerLike">
        <el-input v-model="queryParams.executorHandlerLike" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item label="状态">
        <dict-selector dictType="job_log_status" :value="queryParams.logStatus" @change="(val) => queryParams.logStatus=val" style="width:240px" />
      </el-form-item>
      <el-form-item label="调度时间">
        <el-date-picker
          v-model="dateRange" size="small" style="width: 240px" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['job:log:view']" />
        <reset-button @click="resetQuery" :perm="['job:log:view']" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <delete-button text="清理日志" @click="handleDelete" :perm="['job:log:remove']" :confirm="false" />
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </el-row>
    <el-table v-loading="loading" :data="logList">
      <!-- <el-table-column prop="jobId" label="任务ID" align="center" width="60"></el-table-column> -->
      <el-table-column prop="executorAddress" label="执行地址" align="center" min-width="160" />
      <el-table-column prop="executorHandler" label="任务Handler" align="center" min-width="160" />
      <el-table-column prop="executorParam" label="执行参数" align="center" min-width="160" :show-overflow-tooltip="true" />
      <el-table-column label="调度信息" align="center">
        <el-table-column prop="triggerTime" label="时间" align="center" width="160" />
        <el-table-column prop="triggerCode" label="结果" align="center" width="80">
          <template #default="scope">
            <span v-if="scope.row.triggerCode==='200'" class="text-navy">成功</span>
            <span v-if="scope.row.triggerCode>'200'" class="text-danger">失败</span>
          </template>
        </el-table-column>
        <el-table-column prop="triggerMsg" label="日志" align="center" width="80">
          <template #default="scope">
            <el-button type="text" @click="handleView(scope.row)" :perm="['job:log:view']">查看</el-button>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="执行信息" align="center">
        <el-table-column prop="handleTime" label="时间" align="center" width="160" />
        <el-table-column prop="handleCode" label="结果" align="center" width="80">
          <template #default="scope">
            <span v-if="scope.row.handleCode==='200'" class="text-navy">成功</span>
            <span v-if="scope.row.handleCode>'200'" class="text-danger">失败</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="handleMsg" label="执行备注" align="center" min-width="150"></el-table-column> -->
        <el-table-column label="日志" align="center" width="80">
          <template #default="scope">
            <el-button type="text" @click="handleExecuteLogView(scope.row)" :perm="['job:log:view']">查看</el-button>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 查看调度日志 -->
    <drag-dialog title="调度日志" :close-on-click-modal="false" v-model="form.open" width="80%" append-to-body>
      <div v-html="form.triggerMsg"></div>
      <template #footer>
        <dialog-footer @cancel="cancel" cancelText="关闭" :showOk="false" />
      </template>
    </drag-dialog>
    <!-- 查看执行日志 -->
    <drag-dialog title="执行日志" :close-on-click-modal="false" v-model="executorForm.open" width="80%" append-to-body>
      <div v-html="executorForm.logContent"></div>
      <template #footer>
        <dialog-footer @cancel="cancel" @ok="doGetExecuteLog" cancelText="关闭" okText="下一页" :okDisabled="executorForm.isEnd" />
      </template>
    </drag-dialog>
    <!-- 清理调度日志 -->
    <drag-dialog title="日志清理" :close-on-click-modal="false" v-model="clearForm.open" width="600px" append-to-body>
      <el-form :model="clearForm" label-width="100px">
        <el-form-item label="执行器" prop="jobGroup">
          <dict-selector :dictData="jobGroupList" :value="queryParams.jobGroup" @change="onJobGroupSelectChanger" />
        </el-form-item>
        <el-form-item label="任务" prop="jobId">
          <dict-selector :dictData="jobInfoList" :value="queryParams.jobId" @change="(val) => queryParams.jobId=val" />
        </el-form-item>
        <el-form-item label="清理范围" prop="cleanType">
          <dict-selector :dictData="jobCleanTypeList" :value="clearForm.cleanType" @change="(val) => clearForm.cleanType=val" :clearable="false" />
        </el-form-item>
      </el-form>
      <template #footer>
        <dialog-footer @ok="doCleanSubmit" @cancel="cancel" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import { logDetailCat, listLog, getLogCleanTypeList, clearLog } from "@job/api/job/log";
import { getJobInfoList } from "@job/api/job/info";
import { debounceWrapper } from "@/utils/zmids";

export default {
  name: "JobLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格树数据
      logList: [],
      // 执行器列表
      jobGroupList: [],
      // 任务列表
      jobInfoList: [],
      // 任务清理类型列表
      jobCleanTypeList: [],
      queryParams: {
        jobGroup: '',
        pageNum: 1,
        pageSize: 10,
        orderBy: 'TRIGGER_TIME',
        sortDirect: 'DESC'
      },
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 执行日志窗口
      executorForm: {},
      // 清理窗口
      clearForm: {},
    }
  },
  created() {
    this.resetForm();
    this.getList();
    this.getDicts("job_groups").then(response => {
      this.jobGroupList = response.data;
    });
    this.doGetLogCleanTypeList();
  },
  methods: {
    // 重置Form表单
    resetForm() {
      this.form = {
        open: false,
        triggerMsg: "",
      };
      this.executorForm = {
        open: false,
        logId: undefined,
        fromLineNum: 1,
        isEnd: false,
        logContent: '',
      };
      this.clearForm = {
        open: false,
        cleanType: '',
      };
    },
    // 执行器下拉框选项改变
    onJobGroupSelectChanger: debounceWrapper(function (val) {
      this.queryParams.jobGroup = val;
      this.queryParams.jobId = '';
      this.clearForm.jobGroup = val;
      this.clearForm.jobId = '';
      getJobInfoList(this.queryParams.jobGroup)
        .then((response) => {
          this.jobInfoList = response.data;
        });
    }),
    // 获取日志清理类型列表
    doGetLogCleanTypeList: debounceWrapper(function () {
      getLogCleanTypeList().then(response => {
        this.jobCleanTypeList = response.data;
        if (this.jobCleanTypeList != null && this.jobCleanTypeList.length > 0) {
          this.clearForm.cleanType = this.jobCleanTypeList[0].dictValue;
        }
      });
    }),
    // 查询调度日志列表
    getList: debounceWrapper(function () {
      this.loading = true;
      listLog(this.addDateRange(this.queryParams, ['triggerTimeStart', 'triggerTimeEnd'], this.dateRange)).then(
        response => {
          this.logList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        }
      );
    }),
    /** 搜索按钮操作 */
    handleQuery: debounceWrapper(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }),
    /** 重置按钮操作 */
    resetQuery: debounceWrapper(function () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    }),
    /** 查看按钮操作 */
    handleView(row) {
      this.form = {
        open: true,
        triggerMsg: row.triggerMsg,
      }
    },
    /** 查看执行日志按钮操作 */
    handleExecuteLogView: debounceWrapper(function (row) {
      this.loading = true;
      this.executorForm.logId = row.id;
      this.executorForm.logContent = '';
      this.doGetExecuteLog(() => {
        this.loading = false;
        this.executorForm.open = true;
      });
    }),
    // 获取执行日志
    doGetExecuteLog(callback) {
      const params = {
        logId: this.executorForm.logId,
        fromLineNum: this.executorForm.fromLineNum,
      };
      logDetailCat(params).then(response => {
        this.executorForm.fromLineNum = response.data.toLineNum + 1;
        this.executorForm.logContent += '<br>' + response.data.logContent.replaceAll("\n", "<br>");
        if (response.data.end === true) {
          this.executorForm.isEnd = true;
          this.executorForm.logContent += '<br><br><span class="text-success">[日志加载完成]</span>';
        }
        if (typeof callback === 'function') {
          callback();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      this.clearForm = {
        open: true,
      }
    },
    // 取消按钮
    cancel() {
      this.resetForm();
    },
    // 执行清理
    doCleanSubmit: debounceWrapper(function () {
      const params = {
        jobGroup: this.queryParams.jobGroup,
        jobId: this.queryParams.jobId,
        type: this.clearForm.cleanType,
      };
      this.loading = true;
      clearLog(params).then(response => {
        this.loading = false;
        this.msgSuccess("清理成功,共清理" + response.data + "条数据");
        this.resetForm();
        this.handleQuery();
      }).catch(e => {
        this.loading = false;
        console.error(e);
      });
    }),
  }

}
</script>

<style lang="scss" scoped>
</style>